package universum.engine.environment;

import universum.bi.Entity;
import universum.bi.Location;
import universum.engine.TempPublicUniverse;
import universum.engine.Universe;

import java.util.List;
import java.util.ArrayList;

public class MessagingClientProxy implements IMessagingClientProxy, IMessagingClientProxyCallback {
    private IMessagingClient _client;
    private Integer _clientID;
    private IMessagingService _service;
    private String _beingName; // prevent being from being given ext cpu time
    private Universe _universe;
    private List<IEnvironmentService> _envservices;
    private Location _lastLocation;
    private boolean doNotRefreshEnvList = true;
    //private List<IEnvironmentClient> _envclients;

    public MessagingClientProxy() {
        _service = MessagingService.getInstance();        
    }

    public String getName() {
        return _beingName;
    }

    public int getID() {
        return _clientID;
    }

    private void updateEnvList() {
        if (!doNotRefreshEnvList | _envservices == null) {
            if (_envservices == null) _envservices = new ArrayList<IEnvironmentService>();
            Location curLocation = getLocation();
            if (_lastLocation != curLocation) {
                _lastLocation = curLocation;
                _envservices.clear();
                _envservices.addAll(_service.getEnvironments(getLocation()));
            }
        }
    }

    public void setBeing(IMessagingClient being) {
        _universe = TempPublicUniverse.getInstance().getUniverse();
        _client = being;
        _client.setProxy(this); //  Glad to meet you ;)
        _clientID = _universe.getId((Entity) _client);
        _beingName = _client.getName();
    }

    public Location getLocation() {
        return _universe.getLocation(_clientID);
    }

    public IEnvironmentClient getEnvironment(String envName, int envVersion) {
        updateEnvList();
        for (IEnvironmentClient env : _envservices) {
            if (env.getShortName().equals(envName) & env.getVersion() == envVersion) return env;
        }
        return null;
    }

    public IEnvironmentClient getEnvironment(String envName) {
        return getEnvironment(envName, 0);
    }

    public IEnvironmentClient getEnvironment(int index) {
        updateEnvList();
        return _envservices.get(index);
    }

    public List<IAvailableMessage> getMessages() {
        return _service.getMessages(getLocation(), _clientID);
    }

    public INewMessage createMessage(IEnvironmentClient env) {
        updateEnvList();
        return _envservices.get(_envservices.indexOf(env)).createMessage(this); // TODO: unsafe, indexes may not be synchronized
    }

    public int AvailableEnvironmentsCount() {
        updateEnvList();
        return _envservices.size();
    }
}
